package xjf.learn.stream;

import org.junit.Test;
import xjf.base.constant.STATUS;
import xjf.base.entity.Employee;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 1. 归约：reduce——可以将流中元素反复结合起来，得到一个值
 *
 * 2. 收集：collect——将流转换为其他形式。接收一个Collector接口的实现，用于给Stream中元素做汇总的方法
 *
 * @Author: xjf
 * @Date: 2020/4/12 22:19
 */
public class Test4 {

    /**
     * 数据准备
     */
    private List<Employee> employeeList = Arrays.asList(
            new Employee("张三", 45, 6000, STATUS.BUSY),
            new Employee("李四", 20, 7600, STATUS.FREE),
            new Employee("王五", 38, 4900, STATUS.VACATION),
            new Employee("赵六", 77, 2000, STATUS.BUSY),
            new Employee("田七", 54, 6500, STATUS.FREE),
            new Employee("田七", 54, 6500, STATUS.FREE)
    );

    /**
     * 1. 归约
     */
    @Test
    public void test1(){
        // 计算数值累加
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Integer sum = integerList.stream()
                // 第一个参数：起始值。 第二个参数：计算规则
                .reduce(0, (x, y) -> x + y);

        System.out.println(sum);

        System.out.println("======================================= 分割线 =========================================");

        // 计算工资总和
        Double sumSalary = employeeList.stream()
                .map(employee -> employee.getSalary())
                .reduce(0.0, (x, y) -> x + y);
        System.out.println(sumSalary);
    }

    /**
     * 2. 收集
     */
    @Test
    public void test2(){
        List<Employee> resultList = employeeList.stream()
                .filter(employee -> employee.getAge() > 35)
                .collect(Collectors.toList());

        resultList.forEach(System.out::println);
    }
}
